package com.wgts.wgts.mvp.view.fragment;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wgts.wgts.R;
import com.wgts.wgts.base.LazyBaseFragment;
import com.wgts.wgts.control.appBar.AppBarStateChangeListener;
import com.wgts.wgts.control.interploator.ToastInterploator;
import com.wgts.wgts.control.recycleview.CustomLineaLayoutManager;
import com.wgts.wgts.control.toast.MoHuToast;
import com.wgts.wgts.control.viewpage.TimeViewPageAdapter;
import com.wgts.wgts.dagger.ComponentHolder;
import com.wgts.wgts.dagger.component.DaggerHomePageContentFragmentComponent;
import com.wgts.wgts.dagger.module.HomePageContentFragmentModule;
import com.wgts.wgts.mvp.presenter.IHomePageContentFragmentPersenter;
import com.wgts.wgts.mvp.view.IHomePageContentFragmentView;
import com.wgts.wgts.mvp.view.activity.awardmore.AwardMoreActivity;
import com.wgts.wgts.mvp.view.activity.goodsinfo.JDGoodinfoActivity;
import com.wgts.wgts.mvp.view.activity.guessing.GuessingActivity;
import com.wgts.wgts.mvp.view.activity.homapge.BannerViewHolder;
import com.wgts.wgts.mvp.view.activity.homapge.HomePageActionEntryAdapter;
import com.wgts.wgts.mvp.view.activity.homapge.HomePageTimeActionFragment;
import com.wgts.wgts.mvp.view.activity.shopkeeper.UpgradeShopKeeperActivity;
import com.wgts.wgts.mvp.view.activity.todayspecial.HomePageCurrencyActivity;
import com.wgts.wgts.mvp.view.activity.webactivity.WebActivity;
import com.wgts.wgts.mvp.view.callback.IHomePageContentFragmentCallBackActivity;
import com.wgts.wgts.netmodle.resp.ActivityListEntity;
import com.wgts.wgts.netmodle.resp.AppModleEntity;
import com.wgts.wgts.netmodle.resp.VipMessageEntity;
import com.wgts.wgts.tools.AppInfor;
import com.wgts.wgts.tools.CustomImageView;
import com.wgts.wgts.tools.MoHuGlide;
import com.wgts.wgts.tools.Tools;
import com.wgts.wgts.tools.VipMessageDate;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;
import com.zhouwei.mzbanner.holder.MZViewHolder;

import net.lucode.hackware.magicindicator.MagicIndicator;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;

public class HomePageContentFragment extends LazyBaseFragment implements IHomePageContentFragmentView {
    int toolBarPositionY = 0;

    Unbinder unbinder;
    @BindView(R.id.mz_banner)
    MZBannerView mzBanner;
    @BindView(R.id.img_new_people)
    ImageView imgNewPeople;
    @BindView(R.id.tv_new_people)
    TextView tvNewPeople;
    @BindView(R.id.linear_new_people)
    LinearLayout linearNewPeople;
    @BindView(R.id.img_new_goods)
    ImageView imgNewGoods;
    @BindView(R.id.tv_new_goods)
    TextView tvNewGoods;
    @BindView(R.id.linear_new_goods)
    LinearLayout linearNewGoods;
    @BindView(R.id.img_today_special)
    ImageView imgTodaySpecial;
    @BindView(R.id.tv_today_special)
    TextView tvTodaySpecial;
    @BindView(R.id.linear_today_special)
    LinearLayout linearTodaySpecial;
    @BindView(R.id.img_vip)
    ImageView imgVip;
    @BindView(R.id.tv_vip)
    TextView tvVip;
    @BindView(R.id.linear_vip)
    LinearLayout linearVip;
    @BindView(R.id.img_big)
    ImageView imgBig;
    @BindView(R.id.tv_big)
    TextView tvBig;
    @BindView(R.id.linea_big)
    LinearLayout lineaBig;
    @BindView(R.id.gif_webView)
    ImageView gifWebView;
    @BindView(R.id.recycle_view_action_entry)
    RecyclerView recycleViewActionEntry;
    @BindView(R.id.time_table_layout)
    TabLayout timeTableLayout;
    @BindView(R.id.time_app_bar)
    AppBarLayout timeAppBar;
    @BindView(R.id.view_pager)
    ViewPager viewPager;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.magic_indicator_title)
    MagicIndicator magicIndicatorTitle;
    @BindView(R.id.img_head)
    CircleImageView imgHead;
    @BindView(R.id.tv_toast)
    TextView tvToast;

    @BindView(R.id.linea_keep_toast)
    RelativeLayout lineaKeepToast;
    @BindView(R.id.image_top)
    ImageView imageTop;


    private int mOffset = 0;
    private int mScrollY = 0;

    @Inject
    IHomePageContentFragmentPersenter persenter;

    private List<AppModleEntity.AppModleResult> appModleResults;


    private CustomLineaLayoutManager linearLayoutManager, LinearLayoutManager2;

    private IHomePageContentFragmentCallBackActivity homePageContentFragmentCallBackActivity;

    private ObjectAnimator animator;

    private ArrayList<Fragment> timeFragments;


    @Override
    public void init() {
        DaggerHomePageContentFragmentComponent
                .builder()
                .appComponent(ComponentHolder.getInstance().getAppComponent())
                .homePageContentFragmentModule(new HomePageContentFragmentModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.home_page_content_fragment_change, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        return view;
    }

    @Override
    public void onCreate(Bundle saveInstanceBundle) {
        super.onCreate(saveInstanceBundle);
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        homePageContentFragmentCallBackActivity = (IHomePageContentFragmentCallBackActivity) context;
    }

    private void initView() {
        initScrollView();
        initLinearTop();
        persenter.vipMessage();
        animator = ObjectAnimator.ofFloat(lineaKeepToast, "alpha", 0, 1, 0);
        animator.setDuration(7000);
        animator.setInterpolator(new ToastInterploator());
    }

    private void initScrollView() {
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadmore(false);

        refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
//                int fragmentIndex = viewPager.getCurrentItem();
//                if (timeFragments != null && fragmentIndex < timeFragments.size()) {
//                    ((HomePageTimeActionFragment) timeFragments.get(fragmentIndex)).loadMoreTime();
//                }
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                persenter.initDataView();
                persenter.timeActionList();
            }
        });

//        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
//            @Override
//            public void onRefresh(RefreshLayout refreshlayout) {
//                persenter.initDataView();
//                persenter.timeActionList();
//            }
//        });

        timeTableLayout.post(new Runnable() {
            @Override
            public void run() {
                //dealWithViewPager();
            }
        });

        timeAppBar.addOnOffsetChangedListener(new AppBarStateChangeListener() {
            @Override
            public void onStateChanged(AppBarLayout appBarLayout, State state) {
                if (state == State.EXPANDED) {
                    homePageContentFragmentCallBackActivity.showMagicIndicator();
                    Log.d("", "展开状态");
                } else if (state == State.COLLAPSED) {
                    homePageContentFragmentCallBackActivity.hideMagicIndicator();
                    Log.d("", "折叠状态");
                    //折叠状态
                }
            }
        });
    }


    @Override
    protected void loadData() {
        persenter.initDataView();
        persenter.timeActionList();
//        CoordinatorLayout.Behavior behavior =
//                ((CoordinatorLayout.LayoutParams) timeAppBar.getLayoutParams()).getBehavior();
//        if (behavior instanceof AppBarLayout.Behavior) {
//            AppBarLayout.Behavior appBarLayoutBehavior = (AppBarLayout.Behavior) behavior;
//            int topAndBottomOffset = appBarLayoutBehavior.getTopAndBottomOffset();
//            if (topAndBottomOffset != 0) {
//                appBarLayoutBehavior.setTopAndBottomOffset(0);
//            }
//        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        persenter.stopCutDown();
        unbinder.unbind();
    }

    /**
     * 初始化Banner
     */


    private void initBanner(final List<AppModleEntity.AppModleResult> banners) {


        DisplayMetrics outMetrics = Tools.metrics(getActivity());
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(outMetrics.widthPixels, (int) (outMetrics.widthPixels * 0.45));
        mzBanner.setLayoutParams(layoutParams);
        Tools.setViewMargin(mzBanner, true, 0, 0, 44, 10);

        mzBanner.setBannerPageClickListener(new MZBannerView.BannerPageClickListener() {
            @Override
            public void onPageClick(View view, int i) {

                Intent intent = null;

                if (banners.get(i).actionUrlType.equals("0")) {
                    intent = new Intent(getActivity(), WebActivity.class);
                    intent.putExtra(WebActivity.ACTION_URL, banners.get(i).actionUrl);

                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(banners.get(i).actionUrl);
                        switch (jsonObject.getString("code")) {
                            case "5":
                                intent = new Intent(getActivity(), JDGoodinfoActivity.class);
                                intent.putExtra(JDGoodinfoActivity.PRODUCT_ID, jsonObject.getString("param"));
                                intent.putExtra(JDGoodinfoActivity.JOIN_TYPE, JDGoodinfoActivity.NOMAL);
                                break;
                            case "7":
                                intent = new Intent(getActivity(), AwardMoreActivity.class);
                                break;
                            case "8":
                                intent = new Intent(getActivity(), GuessingActivity.class);
                                break;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                if (intent != null) {
                    startActivity(intent);
                }
            }
        });

        mzBanner.setPages(banners, new MZHolderCreator() {
            @Override
            public MZViewHolder createViewHolder() {
                return new BannerViewHolder();
            }
        });
        mzBanner.start();


    }

    private void initRecycleViewEntry(List<AppModleEntity.AppModleResult> appModleResults) {

        this.appModleResults = appModleResults;

        MoHuGlide.getInstance().raduice(getContext(), appModleResults.get(0).sourceUrl, R.mipmap.ic_function_people, imgNewPeople);
        MoHuGlide.getInstance().raduice(getContext(), appModleResults.get(1).sourceUrl, R.mipmap.ic_function_news, imgNewGoods);
        MoHuGlide.getInstance().raduice(getContext(), appModleResults.get(2).sourceUrl, R.mipmap.ic_function_today, imgTodaySpecial);
        MoHuGlide.getInstance().raduice(getContext(), appModleResults.get(3).sourceUrl, R.mipmap.ic_function_member, imgVip);
        MoHuGlide.getInstance().raduice(getContext(), appModleResults.get(4).sourceUrl, R.mipmap.ic_function_suit, imgBig);

        tvNewPeople.setText(appModleResults.get(0).name);
        tvNewGoods.setText(appModleResults.get(1).name);
        tvTodaySpecial.setText(appModleResults.get(2).name);
        tvVip.setText(appModleResults.get(3).name);
        tvBig.setText(appModleResults.get(4).name);

    }

    private void initRecycleViewActionEntry(List<AppModleEntity.AppModleResult> appModleResults) {

        LinearLayoutManager2 = new CustomLineaLayoutManager(getContext());
        LinearLayoutManager2.setOrientation(LinearLayoutManager.HORIZONTAL);
        recycleViewActionEntry.setLayoutManager(LinearLayoutManager2);
        recycleViewActionEntry.setAdapter(new HomePageActionEntryAdapter(getContext(), appModleResults));

        //integers.add()
    }

    private void initWebView(List<AppModleEntity.AppModleResult> appModleResults) {

        CustomImageView.getInstance().customImage(getContext(), gifWebView, (164 / (double) 750));

        if (appModleResults != null && appModleResults.size() >= 2) {
            if (AppInfor.getInstance().getUserState() > 1) {
                MoHuGlide.getInstance().loadGif(getContext(), appModleResults.get(1).sourceUrl, gifWebView);
            } else {
                MoHuGlide.getInstance().loadGif(getContext(), appModleResults.get(0).sourceUrl, gifWebView);
            }
        }

    }


    private void initLinearTop() {
        imageTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //scrollView.smoothScrollTo(0, 0);
            }
        });
    }

    @OnClick({R.id.linear_new_people, R.id.linear_new_goods, R.id.linear_today_special, R.id.linear_vip, R.id.linea_big, R.id.gif_webView})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.linear_new_people:
                jumpToSpecial(appModleResults.get(0), "0");
                break;
            case R.id.linear_new_goods:
                jumpToSpecial(appModleResults.get(1), "1");
                break;
            case R.id.linear_today_special:
                jumpToSpecial(appModleResults.get(2), "2");
                break;
            case R.id.linear_vip:
                jumpToSpecial(appModleResults.get(3), "3");
                break;
            case R.id.linea_big:
                jumpToSpecial(appModleResults.get(4), "4");
                break;
            case R.id.gif_webView:
                newPeopleAction();
                break;
        }
    }

    private void newPeopleAction() {
        Intent intent = null;
        intent = new Intent(getContext(), UpgradeShopKeeperActivity.class);
        startActivity(intent);

    }

    private void jumpToSpecial(AppModleEntity.AppModleResult appModleResult, String position) {

        if (appModleResult.actionUrlType.equals("0")) {
            //TODO go to web View;
        } else {
            Intent intent = new Intent(getContext(), HomePageCurrencyActivity.class);
            intent.putExtra(HomePageCurrencyActivity.ACTIVITYID, appModleResult.actionUrl);
            intent.putExtra(HomePageCurrencyActivity.TITLE, appModleResult.name);
            intent.putExtra(HomePageCurrencyActivity.POSITION, position);
            startActivity(intent);
        }
    }

    @Override
    public void initResult(List<AppModleEntity> appModleEntities) {

        refreshLayout.finishRefresh();

        Log.d("", "");
        for (AppModleEntity entity : appModleEntities) {
            if (entity.type.equals("SCROLL_PIC")) {
                initBanner(entity.result);
            }
            if (entity.type.equals("SHOW_MENU")) {
                //ToDO
                initRecycleViewEntry(entity.result);
            }
            if (entity.type.equals("NEW_WELFARE")) {
                initWebView(entity.result);
            }
            if (entity.type.equals("MH_WELFARE")) {
                initRecycleViewActionEntry(entity.result);
            }
        }
    }

    @Override
    public void toastVipMessage(VipMessageEntity message) {

        if(lineaKeepToast != null){
            lineaKeepToast.setVisibility(View.VISIBLE);
        }
        animator.end();
        tvToast.setText(message.msg);
        MoHuGlide.getInstance().glideImg(getContext(), message.image, imgHead);
        animator.start();
    }

    @Override
    public void actionistResult(List<ActivityListEntity> entities) {

        timeFragments = new ArrayList<>();
        for (ActivityListEntity entity : entities) {
            timeFragments.add(HomePageTimeActionFragment.getInstance(entity, this));
        }


        viewPager.setAdapter(new TimeViewPageAdapter(getContext(), getChildFragmentManager(), timeFragments, entities));

        viewPager.setOffscreenPageLimit(0);


        timeTableLayout.setupWithViewPager(viewPager);
//      添加限时抢购tab
        for (int i = 0; i < entities.size(); i++) {
            TabLayout.Tab tab = timeTableLayout.getTabAt(i);//获得每一个tab
            tab.setCustomView(R.layout.time_tab_item);//给每一个tab设置view
            TextView time = (TextView) tab.getCustomView().findViewById(R.id.time);
            time.setText(entities.get(i).name);
            TextView type = (TextView) tab.getCustomView().findViewById(R.id.type);
            switch (entities.get(i).loading) {
                case "DELETED":
                    type.setText("已结束");
                    break;
                case "PENDING":
                    type.setText("即将开始");
                    break;
                case "ACTIVE":
                    type.setText("正在抢购");
                    viewPager.setCurrentItem(i);
                    timeTableLayout.getTabAt(i).getCustomView().findViewById(R.id.time_tab).setSelected(true);
                    break;
            }

        }

    }

    @Override
    public void vipMessage(List<VipMessageEntity> vipMessageEntitys) {

        if (vipMessageEntitys.size() > 0) {

            VipMessageDate.getInstance().setList(vipMessageEntitys);
            persenter.toastVipMessage();

        } else {

            if(lineaKeepToast != null){
                lineaKeepToast.setVisibility(View.GONE);
            }
        }

    }

    public void loadfinish() {
        refreshLayout.finishLoadmore();
    }

    @Override
    public void onError(int status, String msg) {
        MoHuToast.showToast(msg);
        if(refreshLayout != null){
            refreshLayout.finishRefresh();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
//        //isVisibleToUser这个boolean值表示:该Fragment的UI 用户是否可见
//        if (!isVisibleToUser) {
//            if (homePageContentFragmentCallBackActivity != null){
//                homePageContentFragmentCallBackActivity.showMagicIndicator();
//            }
//        }
    }

}
